package com.yuandian.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yuandian.api.business_monitor.entity.BusinessProcess;
import com.yuandian.api.business_monitor.entity.BusinessResource;
import com.yuandian.api.management.entity.ConfBusiness;
import com.yuandian.api.management.entity.ConfResource;
import com.yuandian.api.management.entity.ConfStep;
import com.yuandian.api.management.entity.ConfSystem;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.management.mapper.ExcelBatchMapper;
import com.yuandian.management.mapper.ExcelBusinessMapper;
import com.yuandian.management.mapper.ExcelStepMapper;
import com.yuandian.management.service.ConfBusinessService;
import com.yuandian.management.service.ConfResourceService;
import com.yuandian.management.service.ConfStepService;
import com.yuandian.management.service.ConfSystemService;
import com.yuandian.management.vo.*;
import com.yuandian.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 定时器处理业务步骤批量数据
 * <p>
 *
 * @author lijunhang
 * @date 2021/9/22
 * @since 1.0.0
 */
@Component
@Slf4j
@EnableScheduling
public class ImportBusinessStepTimer {

	static final String YES_FLAG = "是";
	static final String NO_FLAG = "否";

    @Autowired
	ExcelBusinessMapper excelBusinessMapper;

    @Autowired
	ExcelStepMapper excelStepMapper;

	@Autowired
	ExcelBatchMapper excelBatchMapper;

    @Autowired
	private ConfSystemService confSystemService;

	@Autowired
	private ConfBusinessService confBusinessService;

	@Autowired
	private ConfStepService confStepService;

	@Autowired
	private ConfResourceService confResourceService;


    private static Object ob = new Object();
    private int count = 0;

    @Scheduled(cron="0 */1 * * * ?")
    public void handleBusinessStep() {
        log.info("开始处理导入的业务步骤数据......");
        synchronized (ob) {
            if (count != 0) {
				log.info("业务步骤数据正在处理中......");
                return;
            }

            count += 1;
        }

        try {
			handleBusinessStepDetail();
        } catch (Exception e) {
			log.error("定时处理导入的业务步骤数据 异常......", e);
        } finally {
            synchronized (ob) {
                count = 0;
            }
        }
		log.info("结束处理导入的业务步骤数据......");
    }


	/**
	 * 定时器处理业务步骤数据
	 *
	 */
	@Transactional
	public void handleBusinessStepDetail() {

		// 1、查出未完成导入的流水
		List<ExcelBatch> batchList = excelBusinessMapper.queryNoFinishBatch();

		if (batchList != null && batchList.size() > 0) {
			for (ExcelBatch batch : batchList) {
				// 把该流水对应的业务都查询出来，以防止业务处理了，步骤没有处理，还要重新查相关的数据出来
				List<ExcelBusiness> busList = excelBusinessMapper.timerSelectAllByDataNumber(batch.getDataNumber());
				List<ExcelStep> stepList = excelStepMapper.selectAllByDataNumber(batch.getDataNumber());

				dealBusinessStep(batch, busList, stepList);
			}


		}
	}

		private ResultAction dealBusinessStep(ExcelBatch excelBatch, List<ExcelBusiness> busList, List<ExcelStep> stepList){
			ResultAction action = new ResultAction();

			String currentUser = "admin";

			// 需保持系统名称唯一，需增加系统名的唯一约束
			Map<String, ConfSystem> sysMap = new HashMap<>();
			// 由于业务表没有系统名称，拿系统编码和业务名称作为key，需增加业务名称和系统编码的唯一约束
			Map<String, ConfBusiness> busMap = new HashMap<>();
			Map<String, ConfResource> resMap = new HashMap();

			long startOne = System.currentTimeMillis();
			log.info("---开始读取业务、步骤对应的系统、已存在的业务、业务资源。");

			// 拿到系统名称、业务名称、资源信息，查询对应的表，获取系统列表、业务列表、资源列表
			getInfoMap(sysMap, busMap, resMap, busList, stepList);

			long endOne = System.currentTimeMillis();
			log.info("---结束读取业务、步骤对应的系统、已存在的业务、业务资源，消耗的时间：" + (endOne - startOne));

			// 业务序号作为key
			Map<String, List<ExcelStep>> stepMap = new HashMap<String, List<ExcelStep>>();
			Map<String, List<ExcelStep>> noFinishStepMap = new HashMap<String, List<ExcelStep>>();

			if (stepList != null && stepList.size() > 0) {
				for (ExcelStep step : stepList) {

					stepMap.computeIfAbsent(step.getSequenceNumber(), k -> new ArrayList<ExcelStep>());
					stepMap.get(step.getSequenceNumber()).add(step);

					if (step.getTaskStatus() == 0) {
						noFinishStepMap.computeIfAbsent(step.getSequenceNumber(), k -> new ArrayList<ExcelStep>());
						noFinishStepMap.get(step.getSequenceNumber()).add(step);
					}
				}
			}

			// 第二步：开始处理业务
			long startAllBusiness = System.currentTimeMillis();
			log.info("---开始处理所有的业务和步骤。");

			int num = 1;
			if (busList != null && busList.size() > 0) {
				for (ExcelBusiness business : busList) {
					// 首先判断业务是否处理过，再看看步骤是否处理完了
					if (business.getTaskStatus() == 1 && noFinishStepMap.get(business.getSequenceNumber()) == null) {
						continue;
					}
					long startBusiness = System.currentTimeMillis();
					log.info("---开始逐条处理业务和对应该业务的步骤，处理完之后写入数据库。当前处理第" + num + "条。");
					num++;

					try {
						ConfSystem system = sysMap.get(business.getSystemName());

						ConfBusiness syBus = system == null ? null
								: busMap.get(system.getId() + business.getBusinessName());

						if (business.getTaskStatus() == 0) {
							long startB = System.currentTimeMillis();
							log.info("---开始处理当前业务。");

							if (system == null) {
								business.setReason(business.getReason() + "该业务对应的系统不存在！");
								updateBusinessFail(business, currentUser);

								// 更新步骤为失败状态
								updateStepFailByList(stepMap.get(business.getSequenceNumber()), currentUser, "业务失败导入步骤失败");
								stepMap.remove(business.getSequenceNumber());

								continue;
							}

							business.setSystemCode(String.valueOf(system.getId()));

							// 业务状态不正常，那么步骤也置为失败
							if (business.getBusinessStatus() != null && business.getBusinessStatus() == 1) {
								updateBusinessFail(business, currentUser);

								// 更新步骤为失败状态
								updateStepFailByList(stepMap.get(business.getSequenceNumber()), currentUser, "业务失败导入步骤失败");
								stepMap.remove(business.getSequenceNumber());
								continue;
							}

							boolean isExist = false;
							if (syBus != null) {
								isExist = true;
							}

							String coverFlag = business.getCoverFlag();

							// 如果已经存在，那么查看是否覆盖--如果已经存在，不覆盖，那么不处理业务数据，只处理业务对应的步骤数据
							if (isExist && YES_FLAG.equals(coverFlag)) {
								syBus = saveSynchronousBusiness(syBus, business, isExist, currentUser);
							} else if (!isExist) {
								// 不存在，那么新增
								syBus = saveSynchronousBusiness(syBus, business, isExist, currentUser);
							}

							// 如果保存失败，那么更新该业务导入状态
							if (syBus == null) {
								updateBusinessFail(business, currentUser);
								// 更新步骤为失败状态
								updateStepFailByList(stepMap.get(business.getSequenceNumber()), currentUser, "业务失败导入步骤失败");
								stepMap.remove(business.getSequenceNumber());
								continue;
							}

							long endB = System.currentTimeMillis();
							log.info("---结束处理当前业务消耗时间：" + (endB - startB));

							if (isExist && YES_FLAG.equals(business.getClearStep())) {
								long startClearStep = System.currentTimeMillis();
								log.info("---清空当前业务步骤：");
								BusinessProcess process = new BusinessProcess();
								process.setSystemCoding(String.valueOf(system.getId()));
								process.setBusinessCode(syBus.getBusinessCode());
								process.setMatching(-1);
								process.setFindTotal(-1);
								process.setMatchAmount(-1);
								process.setStatus(-1);

//								List<BusinessProcess> porcessList = businessProcessReadDao.queryList(process);
								LambdaQueryWrapper<ConfStep> stepQueryWrapper = Wrappers.lambdaQuery();
								stepQueryWrapper.eq(ConfStep::getSystemId, system.getId());
								stepQueryWrapper.eq(ConfStep::getBusinessCode, syBus.getBusinessCode());
								List<ConfStep> porcessList = confStepService.list(stepQueryWrapper);
								if (porcessList != null && porcessList.size() > 0) {
									for (ConfStep step : porcessList) {
										ResultAction result = delete(String.valueOf(step.getId()),
												syBus.getBusinessCode());
										if (ActionState.FAILURE.toString().equals(result.getState())) {
											business.setReason(business.getReason() + "清空步骤失败！");
											updateBusinessFail(business, currentUser);

											// 更新步骤为失败状态
											updateStepFailByList(stepMap.get(business.getSequenceNumber()), currentUser, "清空步骤失败！");
											break;
										}
									}
								}

								long endClearStep = System.currentTimeMillis();
								log.info("---清空当前业务步骤 消耗时间：" + (endClearStep - startClearStep));
							}

							// 更新业务状态为成功处理状态
							business.setBusinessCode(syBus.getBusinessCode());
							business.setBusinessStatus(0);
							business.setTaskStatus(1); // 定时任务处理完成
							excelBusinessMapper.updateExcelBusinessById(business);
						}

						// 第三步：处理定时器未处理的步骤
						long startStep = System.currentTimeMillis();
						log.info("---开始处理当前业务下的步骤：");

						List<ExcelStep> exStepList = stepMap.get(business.getSequenceNumber());
						if (exStepList != null && exStepList.size() > 0) {
							int i = 0;
							for (ExcelStep step : exStepList) {
								try {
									// 已结校验失败的不再处理步骤，或者定时器已经处理过的
									if ((step.getDealStatus() != null && step.getDealStatus() == 1) || step.getTaskStatus() == 1) {
										// 已经处理过，且成功状态加1
										if (step.getDealStatus() == 0) {
											i++;
										}
										if (step.getDealStatus() == 1) {
											step.setUpdateBy(currentUser);
											step.setUpdateTime(new Date());
											step.setTaskStatus(1);
											excelStepMapper.updateStepByid(step);
										}

										continue;
									}

									ConfResource resource = resMap.get(step.getResource());
									if (resource == null) {
										step.setReason("业务资源不存在！");
										updateStepFail(step, currentUser);
										continue;
									}

									if (system == null) {
										step.setReason("系统不存在！");
										updateStepFail(step, currentUser);
										continue;
									}

									if (syBus == null) {
										step.setReason("业务不存在！");
										updateStepFail(step, currentUser);
										continue;
									}

									//判断步骤名称是否已经存在，如果存在，不允许新增，只能情况
									BusinessProcess process = new BusinessProcess();
									process.setSystemCoding(String.valueOf(system.getId()));
									process.setBusinessCode(syBus.getBusinessCode());
									process.setName(step.getStepName());
									process.setMatching(-1);
									process.setFindTotal(-1);
									process.setMatchAmount(-1);
									process.setStatus(-1);

									LambdaQueryWrapper<ConfStep> stepQuery = Wrappers.lambdaQuery();
									stepQuery.eq(ConfStep::getSystemId, system.getId());
									stepQuery.eq(ConfStep::getBusinessCode, syBus.getBusinessCode());
									stepQuery.eq(ConfStep::getName, step.getStepName());
									List<ConfStep> porcessList = confStepService.list(stepQuery);

//									List<BusinessProcess> porcessList = businessProcessReadDao.queryList(process);
									boolean tag = true;
									for (ConfStep businessProcess : porcessList) {
										if (step.getStepName().equals(businessProcess.getName())) {
											step.setReason("步骤已存在，修改步骤名称！");
											updateStepFail(step, currentUser);
											tag = false;
											break;
										}
										;
									}

									if (tag) {
										saveBusinessProcess(step, resource, syBus, system, currentUser);
									}


									step.setUpdateBy(currentUser);
									step.setUpdateTime(new Date());
									step.setTaskStatus(1);
									excelStepMapper.updateStepByid(step);

									// 保存成功加1
									if (step.getDealStatus() == 0) {
										i++;
									}
								} catch (Exception e) {
									step.setReason("保存失败！");
									updateStepFail(step, currentUser);
								}
							}//end for

							if (i == 0) {
								// 全部失败
								business.setStepStatus(1);
							} else if (i == exStepList.size()) {
								// 全部成功
								business.setStepStatus(0);
							} else {
								// 部分失败
								business.setStepStatus(2);
							}
							excelBusinessMapper.updateExcelBusinessById(business);
						}

						long endStep = System.currentTimeMillis();
						log.info("---处理当前业务下的步骤 消耗的时间：" + (endStep - startStep));

					} catch (Exception e) {

						log.error(e.getMessage());
						business.setBusinessStatus(1);
						business.setReason(business.getReason() + "业务处理失败！");
						excelBusinessMapper.updateExcelBusinessById(business);
						// 更新步骤为失败状态
						updateStepFailByList(stepMap.get(business.getSequenceNumber()), currentUser, "业务失败导入步骤失败");
					}

					long endBusiness = System.currentTimeMillis();
					log.info("---结束逐条处理业务和对应该业务的步骤，处理完之后写入数据库。" + (endBusiness - startBusiness));
				}
			}

			long endAllBusiness = System.currentTimeMillis();
			log.debug("---结束处理所有的业务和步骤。" + (endAllBusiness - startAllBusiness));

			long startExport = System.currentTimeMillis();
			log.debug("---开始导出excel文件到本地。");
			// 生成excel到本地
//        createExcel(excelBatch.getDataNumber());
			long endExport = System.currentTimeMillis();
			log.debug("---结束导出excel文件到本地消耗的时间：" + (endExport - startExport));

			excelBatch.setDealStatus(1);
			excelBatch.setUpdateBy(currentUser);
			excelBatch.setUpdateTime(new Date());

			excelBatchMapper.updateBatchByDataNumber(excelBatch);

			return action;
		}

	/**
	 * 保存步骤信息
	 *
	 * @param step
	 * @param resource
	 * @param bus
	 * @param system
	 * @param currentUser
	 */
	private void saveBusinessProcess(ExcelStep step, ConfResource resource, ConfBusiness bus, ConfSystem system,
									 String currentUser) {
		ConfStep bp = new ConfStep();

		try {
			bp.setName(step.getStepName());

			if ("首步骤".equals(step.getStepType())) {
				bp.setType(1);
			} else if ("中间步骤".equals(step.getStepType())) {
				bp.setType(2);
			} else {
				bp.setType(3);
			}

			bp.setStepCode(resource.getResourceCode());
			// bp.setBusSingleRelationshipId(busSingleRelationshipId);

			bp.setCreateBy(currentUser);
			bp.setCreateTime(LocalDateTime.now());
			bp.setSystemId(system.getId());

			// bp.setFuncModuleName(vo.getFuncModuleName());
			bp.setSequence(Integer.parseInt(step.getSequence()));

			boolean confirmFlag = false;
			if (YES_FLAG.equals(step.getConfirmFlag())) {
				bp.setIsConfirm(1);
				confirmFlag = true;
			} else {
				bp.setIsConfirm(0);
			}

			if (YES_FLAG.equals(step.getIsAllowFail())) {
				bp.setIsAllowFail(1);
			} else {
				bp.setIsAllowFail(0);
			}
//
			if (YES_FLAG.equals(step.getIsAllowLose())) {
				bp.setIsAllowLose(1);
			} else {
				bp.setIsAllowLose(0);
			}

			ResultAction result = save4ExcelImport(bus, bp, confirmFlag);

			if (ActionState.FAILURE.toString().equals(result.getState())) {
				step.setDealStatus(1);
				String message = result.getMessage() == null ? "" : result.getMessage();
				step.setReason(step.getReason() + "保存失败！" + message);
			} else {
				step.setDealStatus(0);
			}
			step.setSystemCode(String.valueOf(system.getId()));
			step.setSystemName(system.getName());
			step.setBusinessCode(bus.getBusinessCode());
			step.setBusinessName(bus.getName());
		} catch (Exception e) {

			log.error(e.getMessage());
			step.setDealStatus(1);
			step.setReason(step.getReason() + "保存失败！");
		}
	}

	/**
	 * excel导入保存步骤--同时根据是否确认增加确认逻辑
	 * @param business
	 * @param process
	 * @param confirmFlag
	 * @return
	 */
	public ResultAction save4ExcelImport(ConfBusiness business, ConfStep process, boolean confirmFlag) {
		ResultAction resultAction = new ResultAction();
		try {
//			if (business != null && !org.springframework.util.StringUtils.isEmpty(business.getStepSet())
//					&& business.getStepSet().equalsIgnoreCase("1") && !org.springframework.util.StringUtils.isEmpty(process.getStepType())
//					&& !process.getStepType().equalsIgnoreCase("1")) {
//				resultAction.setState(ActionState.FAILURE.toString());
//				resultAction.setMessage("该业务只能存在首步骤，请修改步骤类型!");
//				return resultAction;
//			} else if (business != null && !org.springframework.util.StringUtils.isEmpty(business.getStepSet())
//					&& business.getStepSet().equalsIgnoreCase("2") && !org.springframework.util.StringUtils.isEmpty(process.getStepType())
//					&& process.getStepType().equalsIgnoreCase("2")) {
//				resultAction.setState(ActionState.FAILURE.toString());
//				resultAction.setMessage("该业务只能存在首末步骤，请修改步骤类型!");
//				return resultAction;
//			}

//			Integer businessSingleRelationshipId = saveBusinessSingleRelationship(business.getResourceCoding(),
//					process.getManualBusinessCode(), "");
//
//			process.setBusSingleRelationshipId(businessSingleRelationshipId);

			process.setBusinessCode(business.getBusinessCode());
			process.setStepCode(process.getStepCode());
			ConfStep bp = confStepService.saveBusinessProcess(process);

			//处理确认逻辑，步骤本身的状态由组装数据那里判断
			if(confirmFlag && bp != null && bp.getId() != null) {
				String[] idArray = {String.valueOf(bp.getId())};
				List<String> stepCodeList = getStepResourceCoding(idArray);
				saveResourceStatus(stepCodeList, 2);
//				List<String> itemCodeList = getItemResourceCoding(stepCodeList);
//				saveResourceStatus(itemCodeList, 1);
//				List<String> firstList = new ArrayList<String>();
//				firstList.addAll(stepCodeList);
//				firstList.addAll(itemCodeList);
//				List<String> afterCodeList = getAllAfterResourceCoding(firstList);
//				saveResourceStatus(afterCodeList, null);
			}

			resultAction.setId(String.valueOf(bp.getId()));
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			resultAction.setState(ActionState.FAILURE.toString());
		}
		return resultAction;
	}




	private List<String> getStepResourceCoding(String[] idArray){
		List<String> resultList = new ArrayList<String>();
		BusinessProcess bp = new BusinessProcess();
		List<Integer> list = new ArrayList<>();
		for (int i = 0; i <idArray.length ; i++) {
			String id=idArray[i];
			int idInt=Integer.parseInt(id);
			list.add(idInt);
		}
		List<ConfStep> bpList = confStepService.listByIds(list);
		for(ConfStep pojo : bpList){
			resultList.add(pojo.getStepCode());
		}
		return resultList;
	}


	private void saveResourceStatus(List<String> list, Integer category) {
		if(!CollectionUtils.isEmpty(list)){

			for (String resourceCoding : list) {
				confResourceService.syncParentResourceExclusiveIndicators(resourceCoding);
			}

			BusinessResource br = new BusinessResource();
			br.setStringlist(list);
			if(category!=null){
				br.setCategory(category);
			}
			br.setIsStatus(1);
			confResourceService.updateByResourceCodes(br);
		}
	}




	/**
	 * 更新步骤
	 *
	 * @param step
	 * @param currentUser
	 */
	private void updateStepFail(ExcelStep step, String currentUser) {
		step.setTaskStatus(1);
		step.setDealStatus(1);
		step.setUpdateBy(currentUser);
		step.setUpdateTime(new Date());
		excelStepMapper.updateStepByid(step);
	}



	/**
	 * 查询业务和步骤对应的系统、业务、业务资源
	 *
	 * @param sysMap
	 * @param busMap
	 * @param resMap
	 * @param businessList
	 * @param stepList
	 */
	private void getInfoMap(Map<String, ConfSystem> sysMap, Map<String, ConfBusiness> busMap,
							Map<String, ConfResource> resMap, List<ExcelBusiness> businessList, List<ExcelStep> stepList) {
		// 系统名称，分割多少个查一次，比如500个系统名称，查一次数据库
		List<List<String>> sysList = new ArrayList<List<String>>();
		// 业务名称
		List<List<String>> busList = new ArrayList<List<String>>();

		// 业务服务资源
		List<List<String>> resList = new ArrayList<List<String>>();

		// 1、按系统名称分批查询出系统信息。
		// 2、按业务名称分批查询出业务信息。
		// 3、按资源“识别字符”分批查询出业务资源信息。

		if (businessList != null && businessList.size() > 0) {
			// 系统名称
			List<String> sysNameList = new ArrayList<String>();
			// 业务名称
			List<String> busNameList = new ArrayList<String>();

			for (ExcelBusiness bvo : businessList) {

				if (StringUtils.isNotBlank(bvo.getSystemName()) && !sysNameList.contains(bvo.getSystemName())) {
					sysNameList.add(bvo.getSystemName());
				}

				if (StringUtils.isNotBlank(bvo.getBusinessName()) && !busNameList.contains(bvo.getBusinessName())) {
					busNameList.add(bvo.getBusinessName());
				}

				if (sysNameList.size() > 0) {
					int sysCount = sysNameList.size() % 500;
					if (sysCount == 0) {
						sysList.add(sysNameList);
						sysNameList = new ArrayList<String>();
					}
				}

				if (busNameList.size() > 0) {
					int busCount = busNameList.size() % 500;
					if (busCount == 0) {
						busList.add(busNameList);
						busNameList = new ArrayList<String>();
					}
				}
			}

			// 如果未满500，或者还有多余的
			if (sysNameList.size() > 0) {
				sysList.add(sysNameList);
			}

			if (busNameList.size() > 0) {
				busList.add(busNameList);
			}

			if (stepList != null && stepList.size() > 0) {
				// 业务资源
				List<String> resNameList = new ArrayList<String>();

				for (ExcelStep svo : stepList) {
					if (StringUtils.isNotBlank(svo.getResource()) && !resNameList.contains(svo.getResource())) {
						resNameList.add(svo.getResource());
					}

					if (resNameList.size() > 0) {
						int resCount = resNameList.size() % 300;
						if (resCount == 0) {
							resList.add(resNameList);
							resNameList = new ArrayList<String>();
						}
					}
				}

				// 如果未满300，或者还有多余的
				if (resNameList.size() > 0) {
					resList.add(resNameList);
				}
			}
			// getSystemByName getBusinessByName getResourcesByName
			List<ConfSystem> systemList = sysList.size() > 0 ? getSystemByName(sysList) : new ArrayList<>();
			List<ConfBusiness> bList = busList.size() > 0 ? getBusinessByName(busList) : new ArrayList<>();
			List<ConfResource> resourceList = resList.size() > 0 ? getResourcesByName(resList) : new ArrayList<>();

			if (systemList != null && systemList.size() > 0) {
				for (ConfSystem sys : systemList) {
					sysMap.put(sys.getName(), sys);
				}
			}

			if (bList != null && bList.size() > 0) {
				for (ConfBusiness bus : bList) {
					busMap.put(bus.getSystemId() + bus.getName(), bus);
				}
			}

			if (resourceList != null && resourceList.size() > 0) {
				for (ConfResource res : resourceList) {
					resMap.put(res.getIdentifyStr(), res);
				}
			}

		}
	}

	/**
	 * 根据系统名称查询系统
	 *
	 * @param sysNameList
	 * @return
	 */
	private List<ConfSystem> getSystemByName(List<List<String>> sysNameList) {
		List<ConfSystem> systemList = new ArrayList<>();

		if (sysNameList != null && sysNameList.size() > 0) {
			for (List<String> list : sysNameList) {
				List<ConfSystem> syslist = excelBatchMapper.selectSystemByName(list);
				if (syslist != null && syslist.size() > 0) {
					systemList.addAll(syslist);
				}
			}
		}

		return systemList;
	}


	/**
	 * 根据业务名称查询业务
	 *
	 * @param busNameList
	 * @return
	 */
	private List<ConfBusiness> getBusinessByName(List<List<String>> busNameList) {
		List<ConfBusiness> businessList = new ArrayList<>();

		if (busNameList != null && busNameList.size() > 0) {
			for (List<String> nameList : busNameList) {
				List<ConfBusiness> list = excelBatchMapper.selectBusinessByName(nameList);

				if (list != null && list.size() > 0) {
					businessList.addAll(list);
				}
			}
		}

		return businessList;
	}


	/**
	 * 根据资源“识别字符”查询业务资源
	 *
	 * @param resNameList
	 * @return
	 */
	private List<ConfResource> getResourcesByName(List<List<String>> resNameList) {
		List<ConfResource> resourceList = new ArrayList<>();

		if (resNameList != null && resNameList.size() > 0) {
			for (List<String> nameList : resNameList) {
				List<ConfResource> list = excelBatchMapper.selectResourceByName(nameList);

				if (list != null && list.size() > 0) {
					resourceList.addAll(list);
				}
			}
		}

		return resourceList;
	}

	/**
	 * 更新业务失败
	 *
	 * @param currentUser
	 */
	private void updateBusinessFail(ExcelBusiness business, String currentUser) {
		business.setStepStatus(1);
		business.setBusinessStatus(1);
		business.setTaskStatus(1);
		business.setUpdateBy(currentUser);
		business.setUpdateTime(new Date());

		excelBusinessMapper.updateExcelBusinessById(business);
	}

	/**
	 * 批量更新步骤
	 *
	 * @param steps
	 * @param currentUser
	 * @param failMessge
	 */
	private void updateStepFailByList(List<ExcelStep> steps, String currentUser, String failMessge) {
		if (steps != null && steps.size() > 0) {
			for (ExcelStep step : steps) {
				if (StringUtils.isNotBlank(failMessge)) {
					step.setReason(step.getReason() + failMessge);
				}

				// 设置失败
				step.setTaskStatus(1);
				step.setDealStatus(1);
				step.setUpdateBy(currentUser);
				step.setUpdateTime(new Date());
				excelStepMapper.updateStepByid(step);
			}
		}
	}

	/**
	 * 删除业务步骤
	 * @param id
	 * @param businessCoding
	 * @return
	 */
	public ResultAction delete(String id, String businessCoding) {
		ResultAction resultAction = new ResultAction();
		try {
			if (!org.springframework.util.StringUtils.isEmpty(id) && !org.springframework.util.StringUtils.isEmpty(businessCoding)) {
				BusinessProcess bp = new BusinessProcess();
//				String[] idArray = id.split(",");
//				for(String uid : idArray){
//					bp.getList().add(Integer.valueOf(uid));
//				}
//				List<BusinessProcess> bpList = businessProcessService.queryStepCount(bp);
				/**
				 * 获取步骤的业务服务资源编码，判断该资源编码是否被其他步骤使用
				 */
				BusinessResource businessResource = new BusinessResource();
				businessResource.setIsStatus(0);
//				List<SingleResourceItRelationship> srirList = new ArrayList<SingleResourceItRelationship>();
//				if(!CollectionUtils.isEmpty(bpList)) {
//					for(BusinessProcess pojo : bpList) {
//						if(pojo.getStepCount().intValue()<=1){
//							businessResource.getStringlist().add(pojo.getManualBusinessCode());
//							SingleResourceItRelationship srir = new SingleResourceItRelationship();
//							srir.setBeforeBusinessResourceCoding(pojo.getManualBusinessCode());
//							srir.setBeforeSegmentId(1);
//						}
//					}
//				}
				// 删除业务步骤，将对应业务服务资源状态改为未确认，同时移除父资源(如果存在)同步过来的专属指标
				for (String resourceCoding : businessResource.getStringlist()) {
					confResourceService.removeParentResourceExclusiveIndicators(resourceCoding);
				}
				confResourceService.updateByResourceCodes(businessResource);
				confStepService.removeByIds(Collections.singleton(id));
			} else {
				resultAction.setState(ActionState.FAILURE.toString());
				resultAction.setMessage("数据传输id失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultAction.setState(ActionState.FAILURE.toString());
		}
		return resultAction;
	}

	/**
	 * 保存业务信息
	 *
	 * @param bus
	 * @param business
	 * @param isExist
	 * @param currentUser
	 * @return
	 */
	private ConfBusiness saveSynchronousBusiness(ConfBusiness bus, ExcelBusiness business, boolean isExist,
														String currentUser) {
		ConfBusiness syBus = new ConfBusiness();

		try {
			// 如果业务已经存在，而且要覆盖
			if (isExist) {
				syBus = bus;
				if (YES_FLAG.equals(business.getKeyBusiness())) {
					syBus.setIsKey(1);
				} else {
					syBus.setIsKey(0);
				}

				if (YES_FLAG.equals(business.getConfirmFlag())) {
//					syBus.setProcessStudyStateInt(3);// 过程学习完成
					syBus.setIsConfirm(1);// 人工确认
//					syBus.setConfirmPeople(currentUser);
//					syBus.setConfirmTime(new Date());
				}

//				if ("1步".equals(business.getStepNum())) {
//					syBus.setStepSet(String.valueOf(1));
//				} else if ("2步".equals(business.getStepNum())) {
//					syBus.setStepSet(String.valueOf(2));
//				} else {
//					syBus.setStepSet(String.valueOf(3));
//				}

				String showOrder = business.getShowOrder() == null ? "0" : business.getShowOrder();
				if ("".equals(showOrder)) {
					syBus.setSequence(0);
				} else {
					syBus.setSequence(Integer.parseInt(showOrder));
				}

//                syBus.setBeginUrl(business.getBeginUrl());
//                syBus.setEndUrl(business.getEndUrl());

				ResultAction result = save4ExcelImport(syBus);

				if (ActionState.FAILURE.toString().equals(result.getState())) {
					syBus = null;
					business.setBusinessStatus(1);
					business.setReason(business.getReason() + result.getMessage());
				}
			} else {
				// 参考页面初始化
//				syBus.setBusinessCredibility("0.8");
//				syBus.setLoadItemCredibility("0");
//				syBus.setSegmentCredibility("80%");
//				syBus.setThresholdAmount(1000);
//				syBus.setStudyCount("10");
//				syBus.setStudyNumThreshold(10);
//
//				syBus.setStudyNum(0);

				syBus.setName(business.getBusinessName());
				syBus.setSystemId(Integer.valueOf(business.getSystemCode()));

				if (YES_FLAG.equals(business.getKeyBusiness())) {
					syBus.setIsKey(1);
				} else {
					syBus.setIsKey(0);
				}

				if (YES_FLAG.equals(business.getConfirmFlag())) {
//					syBus.setProcessStudyStateInt(3);// 过程学习完成
					syBus.setIsConfirm(1);// 人工确认
//					syBus.setConfirmPeople(currentUser);
//					syBus.setConfirmTime(new Date());
				} else {
//					syBus.setProcessStudyStateInt(0);
					syBus.setIsConfirm(0);
//					syBus.setConfirmPeople("");
//					syBus.setConfirmTime(null);
				}

//				if ("1步".equals(business.getStepNum())) {
//					syBus.setStepSet("1");
//				} else if ("2步".equals(business.getStepNum())) {
//					syBus.setStepSet("2");
//				} else {
//					syBus.setStepSet("3");
//				}

				if (YES_FLAG.equals(business.getKeyBusiness())) {
					syBus.setIsKey(1);
				} else {
					syBus.setIsKey(0);
				}

//                syBus.setBeginUrl(business.getBeginUrl());
//                syBus.setEndUrl(business.getEndUrl());
				String showOrder = business.getShowOrder() == null ? "0" : business.getShowOrder();
				if ("".equals(showOrder)) {
					syBus.setSequence(0);
				} else {
					syBus.setSequence(Integer.parseInt(showOrder));
				}

				ResultAction result = save4ExcelImport(syBus);

				if (ActionState.FAILURE.toString().equals(result.getState())) {
					syBus = null;
					business.setBusinessStatus(1);
					business.setReason(business.getReason() + result.getMessage());
				} else {
					// 把业务查出来
					List<ConfBusiness> sbList = confBusinessService.queryBySystemCodeAndName(syBus);
					if (sbList != null && sbList.size() > 0) {
						ConfBusiness confBusiness = sbList.get(0);
						syBus.setBusinessCode(confBusiness.getBusinessCode());
					}
				}
			}
		} catch (Exception e) {

			log.error(e.getMessage());
			business.setBusinessStatus(1);
			business.setReason(business.getReason() + "保存业务失败！");
			syBus = null;
		}

		return syBus;
	}

	/**
	 * excel导入保存业务数据 -- 根据是否确认，直接处理确认
	 * @param business
	 * @return
	 */
	public ResultAction save4ExcelImport(ConfBusiness business) {
		ResultAction resultAction = new ResultAction();
		try {
			if (business != null && !org.springframework.util.StringUtils.isEmpty(business.getId())) {
				ConfBusiness confBusiness = new ConfBusiness();
//				confBusiness.setSequence(business.getShowOrder());
//				confBusiness.setName(business.getName());
//				confBusiness.setIsConfirm(business.getWhetherEnable());
//				confBusiness.setSystemId(Integer.valueOf(business.getSystemCode()));
//				confBusiness.setIsEnable(business.getIsStatus());
//				confBusiness.setIsKey(business.getKeyBusiness());
				//todo 未完成
				R<String> result = null;
				if (business.getId() != null){
					result = confBusinessService.updateBusinessById(confBusiness);
				}else {
					result = confBusinessService.saveBusiness(business);
				}

				if (result.getCode() == -1) {
					resultAction.setState(ActionState.FAILURE.toString());
					resultAction.setMessage("添加业务数量超过可配置数量，请联系源典工作人员...");
					log.error("添加业务数量超过可配置数量，请联系源典工作人员...");
					return resultAction;
				}
			} else {
				// insert 要先和数据库中的数据进行比对，超过最大值不允许添加
//				SynchronousBusiness condition = new SynchronousBusiness();
//				condition.setProcessStudyStateInt(-2);
//				condition.setThresholdAmount(-1);
//				condition.setWhetherEnable(-1);
//				condition.setIsStatus(-1);
//				condition.setStudyNumThreshold(-1);
//				condition.setStudyNum(-1);
//				List<SynchronousBusiness> fristResult = synchronousBusinessService.queryList(condition);
//				boolean compareResult = searchMaxConfig(fristResult.size());
//				if (!compareResult) {
//					resultAction.setState(ActionState.FAILURE.toString());
//					resultAction.setMessage("添加业务数量超过可配置数量，请联系源典工作人员...");
//					log.error("添加业务数量超过可配置数量，请联系源典工作人员...");
//					return resultAction;
//				}
				R<String> result = confBusinessService.saveBusiness(business);
				if (result.getCode() == -1) {
					resultAction.setState(ActionState.FAILURE.toString());
					resultAction.setMessage("添加业务数量超过可配置数量，请联系源典工作人员...");
					log.error("添加业务数量超过可配置数量，请联系源典工作人员...");
					return resultAction;
				}
//				synchronousBusinessService.saveSynchronousBusiness(business);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultAction.setState(ActionState.FAILURE.toString());
			resultAction.setMessage("保存业务失败！");
		}
		return resultAction;
	}



}
